﻿/*******************************************************************************
* 
*Author         :  VN
*Description    :  网络通信模块服务器加密算法封装
*Other          :  none
*Modify Record  :  none
*
*******************************************************************************/
using System;
using UnityEngine;

public class Encryption
{
    const string OrigeSecretKey = "A6204EFACB675DF8";

    byte[] m_curSecretKey = null;
    byte[] m_oldSecretKey = null;

    public void SetSecretKey(byte[] key)
    {
        if (key == null)
        {
            m_curSecretKey = System.Text.Encoding.UTF8.GetBytes(OrigeSecretKey);
            m_oldSecretKey = null;
        }
        else
        {
            m_oldSecretKey = m_curSecretKey;
            m_curSecretKey = key;
        }
    }

    public byte[] Encrypt(byte[] value)
    {
        MakesureInitKey();

        uint iEncryptLen = 0;
        byte[] newData = XXTea.xxtea_encrypt(value, (uint)value.Length, m_curSecretKey, out iEncryptLen);
        return newData;
    }

    public byte[] Decrypt(byte[] value)
    {
        MakesureInitKey();

        uint iEncryptLen = 0;
        byte[] decryptData = XXTea.xxtea_decrypt(value, (uint)value.Length, m_curSecretKey, out iEncryptLen);

        // 用新的解密不成功，尝试旧的
        if (decryptData == null && m_oldSecretKey != null)
        {
            decryptData = XXTea.xxtea_decrypt(value, (uint)value.Length, m_oldSecretKey, out iEncryptLen);
        }
        // 用新的解密成功，则旧的就没用了
        else
        {
            m_oldSecretKey = null;
        }

        return decryptData;
    }

    void MakesureInitKey()
    {
        if (m_curSecretKey == null || m_curSecretKey.Length == 0)
        {
            m_curSecretKey = System.Text.Encoding.UTF8.GetBytes(OrigeSecretKey);
        }
    }

    static public void Test(string str)
    {
        Encryption t = new Encryption();
        byte[] x = t.Encrypt(System.Text.Encoding.UTF8.GetBytes(str));
        string strL = "";
        for (int i = 0; i < x.Length; ++i)
        {
            strL += (int)x[i];
            strL += " ";
        }
    }
}